package com.yhq.basic.thread.juc;

import lombok.SneakyThrows;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author hqyin
 * @date 2023/2/28 4:08 下午
 */
public class TestUnsafe {
    static int a = 0, b = 0, x = 0, y = 0;

    @SneakyThrows
    public static void main(String[] args) {
        int i = 0;
        while (true) {
            i++;
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    a = 1;
                    //防止指令重排
                    getUnsafe().fullFence();
                    x = b;
                }
            });

            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y = a;
                }
            });

            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();

            System.out.println("第" + i + "次循环，结果：(x,y):(" + x + "," + y + ")");
            if (x == 0 && y == 0) {
                break;
            }
        }

    }

    @SneakyThrows
    public static Unsafe getUnsafe() {
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe) field.get(null);

    }
}
